package com.cxz.kotlin.baselibs.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 应用程序Activity管理类
 *
 * @author gyc
 * @created 2017-8-7
 */
public class AppManager {

    public ArrayList<Activity> getActivityStack() {
        return activityStack;
    }

    private ArrayList<Activity> activityStack = new ArrayList<>();
    private static AppManager instance;
    /**
     * 手机端启动烹饪后的堆栈
     */
    private ArrayList<Activity> mMobileStartCookingStack;

    private int stateCount = 0;

    private AppManager() {
    }

    /**
     * 单一实例
     */
    public static AppManager getAppManager() {
        if (instance == null) {
            instance = new AppManager();
        }
        return instance;
    }

    public void addStateCount() {
        stateCount++;
    }

    public void decStateCount() {
        stateCount--;
    }

    public boolean isAppBackground() {
        return stateCount <= 0;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        try {
            if (activityStack.size() >= 1) {
                return activityStack.get(activityStack.size() - 1);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        finishActivity(currentActivity());
    }


    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
            if (!activity.isFinishing() && !activity.isDestroyed()) {
                activity.finish();
            }
            activity = null;
        }
    }

    /**
     * 移除Act 除了 cls
     *
     * @param cls
     */
    public void finishAllActExcept(Class<?> cls) {
        if (activityStack.isEmpty()) {
            return;
        }
        synchronized (activityStack) {
            for (int i = activityStack.size() - 1; i >= 0; i--) {
                Activity activity = activityStack.get(i);
                if (!activity.getClass().equals(cls)) {
                    finishActivity(activity);
                }
            }
        }
    }

    public void finishAllActExcept(Class<?>... clss ) {
        if (activityStack.isEmpty()) {
            return;
        }
        synchronized (activityStack) {
            for (int i = activityStack.size() - 1; i >= 0; i--) {
                Activity activity = activityStack.get(i);
                boolean needFinish = true;
                for (Class cls: clss) {
                    if (activity.getClass().equals(cls)) {
                        needFinish = false;
                    }
                }
                if (needFinish) {
                    finishActivity(activity);
                }
            }
        }
    }


    /**
     * 判断是否在情节页面
     */
    public boolean isInCleanPage() {

        if (activityStack.isEmpty()) {
            return false;
        }
        synchronized (activityStack) {
            for (int i = activityStack.size() - 1; i >= 0; i--) {
                Activity activity = activityStack.get(i);
                if (activity.getClass().getName().contains("com.galanz.ovena6.ui.clean")) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 移除Act 除了 cls
     *
     * @param actName
     */
    synchronized public void finishAllActExcept(String actName) {
        Class<?> cls = null;
        try {
            cls = Class.forName(actName);
            finishAllActExcept(cls);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (activityStack.isEmpty()) {
            return;
        }
        for (int i = activityStack.size() - 1; i >= 0; i--) {
            Activity activity = activityStack.get(i);
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 结束指定类名的Activity by String
     */
    public void finishActivity(String actName) {
        if (TextUtils.isEmpty(actName)) {
            return;
        }
        try {
            Class<?> cls = Class.forName(actName);
            finishActivity(cls);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {
                Activity activity = activityStack.get(i);
                if (!activity.isFinishing()) {
                    activity.finish();
                }
            }
        }
        activityStack.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit() {
        try {
            finishAllActivity();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    /**
     * 移除页面
     */
    public void removeActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }
    }


    /**
     * 判断某个界面是否在前台,返回true，为显示,否则不是
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }



}